package com.leviassaf.androidbasics;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode.VmPolicy;
import android.text.InputFilter.LengthFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class Camera extends Activity implements OnClickListener {

	ImageButton imgbtnSelectPicture;
	Button btnSetWallpaper;
	ImageView imgvwSelectedImage;
	Intent intentMediaStoreImgCapture;
	int intCameraData = 0;
	//40
	Bitmap bmpSelectedImage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo);
		setJavaRefs();
		//42
		//These 2 lines set the bitmap to default to a default image from the drawable folder
//		InputStream inputstream = getResources().openRawResource(R.drawable.ic_launcher);
//		bmpSelectedImage = BitmapFactory.decodeStream(inputstream);

		this.setTitle(String.format("%s-%s", this.getTitle().toString(), this.getClass().getSimpleName()));
	}

	private void setJavaRefs() {
		// TODO Auto-generated method stub
		imgvwSelectedImage = (ImageView)findViewById(R.id.imgvwSelectedImage);
		imgbtnSelectPicture = (ImageButton)findViewById(R.id.imgbtnSelectPicture);
		btnSetWallpaper = (Button)findViewById(R.id.btnSetWallpaper);
		btnSetWallpaper.setOnClickListener(this);
		imgbtnSelectPicture.setOnClickListener(this);
	}

	//39
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.btnSetWallpaper:
			try {
				//42
				if (bmpSelectedImage != null){
					//41
					WallpaperManager.getInstance(getApplicationContext()).setBitmap(bmpSelectedImage);
				}
				else{
					Toast.makeText(this, "First click the image button to take a picture dude!", Toast.LENGTH_SHORT).show();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.imgbtnSelectPicture:
			intentMediaStoreImgCapture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intentMediaStoreImgCapture, intCameraData);
			break;
		}
	}

	//40
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK){
			Bundle bndlExtras = data.getExtras();
			bmpSelectedImage = (Bitmap)bndlExtras.get("data");
			imgvwSelectedImage.setImageBitmap(bmpSelectedImage);
		}
	}

}
